package spring.dao.ejemplos.tasks.dao.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.MappingSqlQuery;

import spring.dao.ejemplos.tasks.dao.TaskDAO;
import spring.dao.ejemplos.tasks.model.Task;

public class JDBCMappingQueryTaskDao implements TaskDAO {
	
	private JdbcTemplate jdbcTemplate;
	
	public void addTask(Task task) {
		String sql = "INSERT INTO tasks (id, summary, completed, user) VALUES (?,?,?,?)";
		Object[] args = new Object[]{task.getId(), task.getSummary(), task.isComplete(),task.getUser()};
		int[] types = new int[]{Types.INTEGER, Types.VARCHAR, Types.BOOLEAN, Types.VARCHAR};
		jdbcTemplate.update(sql,args,types);
	}

	public Task getTask(int id) {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Task> getTasks(String username) {
		TaskByUserMappingQuery query = new TaskByUserMappingQuery(jdbcTemplate.getDataSource());
		Object[] params = {username};
		
		List tasks = query.execute(params);
		return tasks;
	}
	
	private class TaskByUserMappingQuery extends MappingSqlQuery{
		public TaskByUserMappingQuery (DataSource ds){
			super(ds, "select * from tasks where user = ?");
			super.declareParameter(new SqlParameter("user", Types.VARCHAR));
			compile();
		}
		protected Object mapRow(ResultSet rs, int rowIndex) throws SQLException {
			Task t = new Task();
			t.setId(rs.getInt("id"));
			t.setSummary(rs.getString("summary"));
			t.setComplete(rs.getBoolean("completed"));
			t.setUser(rs.getString("user"));
			return t;			
		}
	}
	public void updateTask(Task task) {
		// TODO Auto-generated method stub

	}
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void transferTask(String fromUser, String toUser, Task task) {
		// TODO Auto-generated method stub
		
	}

}
